<!--
功能：聊天界面展示,
作者：RanSheng,
邮箱：1534677527@qq.com",
时间：2021/6/10 17:07,
版本：v1.0,
修改记录：,
修改内容：,
修改人员：,
修改时间：,
-->

<template>
  <div>
    <div class="chat">

    </div>
    <div class="input">
      <el-input
        type="textarea"
        :rows="2"
        placeholder="请输入内容"
        v-model="textarea">
      </el-input>
      <el-button type="primary" @click="hello">消息发送</el-button>
    </div>
  </div>
</template>

<script>
import {mapState} from "vuex";
import {message} from "@/utils/age";

export default {
  data() {
    return {
      textarea: '',
      socket: '',
      path: ''
    };
  },
  components: {},
  computed: {
    ...mapState(["user"])
  },
  mounted() {
    this.init()
  },
  methods: {

    //初始化
    init() {
      if (typeof (WebSocket) === "undefined") {
        message("warning", "你的浏览器不支持WebSocket")
      } else {
        // 实例化socket
        this.socket = new WebSocket('ws://localhost:9999/chat')
        console.log(this.socket)
        // 监听socket连接
        this.socket.onopen = this.open
        //断开
        this.socket.onclose=this.close
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },

    open () {
      // this.socket.send("123")
      console.log("socket连接成功")
    },
    error () {
      console.log("连接错误")
    },
    getMessage (msg) {
      console.log(msg.data)
    },
    send (params) {
      this.socket.send(params)
    },
    close () {
      console.log("socket已经关闭")
    },


    hello() {
      //  数据整合
      this.socket.send("params")
      // let chat = {
      //   uid: this.user.id,
      //   txt: this.textarea
      // }
      // //  数据发送
      // this.$http.post('', chat).then(response => {
      //   console.log(response.data)
      //   message("success", "成功")
      // }).catch(err => {
      //   message("error", "请求参数错误")
      // })
    }
  },
  watch: {},
  destroyed() {
// 销毁监听
    this.socket.onclose = this.close
  },
}
</script>

<style scoped>
.chat {
  width: 100%;
  height: 300px;
  overflow: scroll;
  background-color: pink;
}

.input {
  height: 100px;
  background-color: pink;
  margin-top: 50px;
}
</style>
